package com.ffcc.fitness.websocket.handler;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 测试WebSocket处理器 - 无需token验证
 */
@Component
@ServerEndpoint(value = "/websocket/test/{userId}")
public class TestWebSocketHandler {
    
    // 存储用户连接
    private static final Map<Long, Session> TEST_SESSIONS = new ConcurrentHashMap<>();
    
    /**
     * 连接建立
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {
        System.out.println("=== 测试WebSocket连接成功 ===");
        System.out.println("用户ID: " + userId);
        System.out.println("Session ID: " + session.getId());
        System.out.println("Request URI: " + session.getRequestURI());
        
        TEST_SESSIONS.put(userId, session);
        
        // 发送欢迎消息
        try {
            session.getBasicRemote().sendText("连接成功，欢迎用户: " + userId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam("userId") Long userId) {
        TEST_SESSIONS.remove(userId);
        System.out.println("测试WebSocket用户 " + userId + " 断开连接");
    }
    
    /**
     * 接收消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam("userId") Long userId) {
        System.out.println("收到用户 " + userId + " 的消息: " + message);
        
        try {
            Session session = TEST_SESSIONS.get(userId);
            if (session != null && session.isOpen()) {
                session.getBasicRemote().sendText("服务器收到消息: " + message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 错误处理
     */
    @OnError
    public void onError(Session session, Throwable error, @PathParam("userId") Long userId) {
        System.err.println("测试WebSocket用户 " + userId + " 连接错误: " + error.getMessage());
        error.printStackTrace();
    }
}
